package com.cisystem.web.controller.business;

import com.alibaba.fastjson2.JSONObject;
import com.cisystem.common.core.controller.BaseController;
import com.cisystem.common.core.domain.AjaxResult;
import com.cisystem.common.core.domain.model.LoginUser;
import com.cisystem.common.exception.base.BaseException;
import com.cisystem.common.utils.SecurityUtils;
import com.cisystem.common.utils.StringUtils;
import com.cisystem.framework.web.service.PermissionService;
import com.cisystem.framework.web.service.SysPermissionService;
import com.cisystem.framework.web.service.TokenService;
import com.cisystem.system.service.ISysUserService;
import com.cisystem.system.service.impl.SysMenuServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

@RestController
@RequestMapping("/business/dcc")
public class PdfController extends BaseController {

    @Autowired
    SysMenuServiceImpl menuService;

    @Autowired
    PermissionService permissionService;

    @Autowired
    TokenService tokenService;

    @Autowired
    SysPermissionService sysPermissionService;

    @Autowired
    ISysUserService userService;

    @GetMapping("/list")
    public AjaxResult listPdfFiles(String filePath) throws FileNotFoundException {
        // [{"tagName":"name","files":[{"fileName":"a","filePath":"path"},{}]}]
        Map<String, Object> subMap = new HashMap<>();
        subMap.put("files", new ArrayList<String>());
        subMap.put("dir", new ArrayList<HashMap<String, Object>>());
        subMap.put("path", filePath);
        // 读取所有的文件
        readFile(subMap);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Set<String> permissions = loginUser.getPermissions();
        if (permissionService.hasPermissions(permissions,"")){
            // 如果有所有权限，直接返回
            return success(parseTypeData(subMap,Arrays.asList("all")));
        }else{
            String prefix = "business:dccfile:";
            // 获取所有对应文件夹的权限
            List<Map<String, Object>> dirs = (List<Map<String, Object>>)subMap.get("dir");
            List<String> newTabList = new ArrayList<>();
            if (CollectionUtils.isEmpty(dirs)){
                return success(subMap);
            }
            //获取权限文件夹
            for (String permission : permissions) {
                // 判断是否是文件夹相关的权限
                if (permission.startsWith(prefix)){
                    // 获取文件夹名称
                    String fireDir = permission.substring(prefix.length());
                    newTabList.add(fireDir);

                }
            }
            subMap.put("dir",dirs);
            return success(parseTypeData(subMap,newTabList));
        }
    }

    //TODO 这里需要不同DCC的需求条件，这里需要再次进行确定，规则是忽略大小写，以及将对应的DCC中的Other页签进行单独显示
    //TODO 该需求模块中的Other部分进行集中展示
    private List<JSONObject> parseTypeData(Map<String, Object> subMap,List<String> tabList) {
        // [{name:[{"fileName":"a","filePath":"path"}]}]
        /*
        Map<String, Object> subMap = new HashMap<>();
        subMap.put("files", new ArrayList<String>());
        subMap.put("dir", new ArrayList<HashMap<String, Object>>());
        subMap.put("path", filePath);
         */
        // [{"fileName":"a","filePath":"path"},{}]
        List<JSONObject> list = new ArrayList<>();
        parseTypeData2(list,subMap);
        Map<String,List<JSONObject>> result = new HashMap<>();
        if (!CollectionUtils.isEmpty(list)){
            // 遍历转化后的数据
            list.forEach(item ->{
                String fileName = item.getString("fileName");
                // 查找下划线
                int first = fileName.indexOf("_");
                // 没有_放到other
                if (first < 0){
                    List<JSONObject> other = result.get("other");
                    if (null == other){
                        List<JSONObject> ch = new ArrayList<>();
                        ch.add(item);
                        result.put("other",ch);
                    }else {
                        other.add(item);
                    }
                }else{
                    // 从第一个_ 开始截取
                    String substring = fileName.substring(first);
                    if (substring.length() > 1){
                        // 查找第二个_
                        int last = substring.indexOf("_", 1);
                        // 没有_放到other
                        if(last<0){
                            List<JSONObject> other = result.get("other");
                            if (null == other){
                                List<JSONObject> ch = new ArrayList<>();
                                ch.add(item);
                                result.put("other",ch);
                            }else {
                                other.add(item);
                            }
                        }else{
                            // 两个_ 中间字符串
                            String substring1 = substring.substring(1, last);
                            StringBuilder newStr = new StringBuilder();
                            for (int i = 0; i < substring1.length(); i++) {
                                char c = substring1.charAt(i);
                                if (c >= 'a' && c <= 'z'){
                                    c = (char)(c-32);

                                }
                                newStr.append(c);
                            }
                            String key = newStr.toString();
                            if (!tabList.isEmpty()){
                                if (tabList.contains(key) || tabList.size() == 1 && tabList.contains("all")){
                                    List<JSONObject> other1 = result.get(key);
                                    if (null == other1){
                                        List<JSONObject> ch = new ArrayList<>();
                                        ch.add(item);
                                        result.put(newStr.toString(),ch);
                                    }else {
                                        other1.add(item);
                                    }
                                }
                            }

                        }
                    }else{
                        List<JSONObject> other = result.get("other");
                        if (null == other){
                            List<JSONObject> ch = new ArrayList<>();
                            ch.add(item);
                            result.put("other",ch);
                        }else {
                            other.add(item);
                        }
                    }
                }
            });
        }
        List<JSONObject> ll = new ArrayList<>();
        List<JSONObject> other = new ArrayList();
        for (String s : result.keySet()) {
            if(s.equals("other")){
                other = result.get(s);
            }else{
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("tagName",s);
                jsonObject.put("list",result.get(s));
                ll.add(jsonObject);
            }
        }
        if(!tabList.isEmpty()){
            if (tabList.contains("other")  || tabList.size() == 1 && tabList.contains("all")){
                JSONObject  otherJson= new JSONObject();
                otherJson.put("tagName","other");
                otherJson.put("list",other);
                ll.add(otherJson);
            }
        }
       // List<JSONObject> collect = ll.stream().sorted(Comparator.comparing(i -> i.get("tagName").equals("other"))).collect(Collectors.toList());
        return ll;
    }

    private void parseTypeData2(List<JSONObject> list ,Map<String, Object> subMap) {
        ArrayList<String> fileFathers =(ArrayList<String>) subMap.get("files");
        for (String fileFather : fileFathers) {
            // "D:\\testFile\\新建文件夹\\新建文本文档.txt"
            if (StringUtils.isNotEmpty(fileFather)){
                ///{"fileName":"a","filePath":"path"}
                JSONObject object = new JSONObject();
                object.put("filePath",fileFather);
                String[] split = fileFather.split("\\\\");
                object.put("fileName",split[split.length-1]);
                list.add(object);
            }
        }
        ArrayList<Map<String, Object>> mapList =(ArrayList<Map<String, Object>>) subMap.get("dir");
        if (!CollectionUtils.isEmpty(mapList)){
            for (Map<String, Object> stringObjectMap : mapList) {
                parseTypeData2(list,stringObjectMap);
            }
        }
    }


    /**
     * 获取文件权限配置
     */
    @GetMapping("/getFilesConfig")
    @PreAuthorize("@ss.hasPermi('business:dcc:config')")
    public AjaxResult getFilesConfig(){
        return success(menuService.selectFileDirConfig());
    }
    /**
     * 添加文件权限配置
     */
    @GetMapping("/addFilesConfig")
    @PreAuthorize("@ss.hasPermi('business:dcc:config')")
    public AjaxResult addFilesConfig(String fileDirName){
        return success(menuService.addFileDirConfig(fileDirName));
    }
    /**
     * 删除文件权限配置
     */
    @GetMapping("/deleteFilesConfig")
    @PreAuthorize("@ss.hasPermi('business:dcc:config')")
    public AjaxResult deleteFilesConfig(Long menuId){
        menuService.deleteMenuById(menuId);
        // 更新缓存用户权限
        LoginUser loginUser = getLoginUser();
        if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin())
        {
            loginUser.setPermissions(sysPermissionService.getMenuPermission(loginUser.getUser()));
            loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
            tokenService.setLoginUser(loginUser);
        }
        return success();
    }
    /**
     * 读取某个文件夹下的所有文件
     *
     */
    @SuppressWarnings("unchecked")
    public void readFile(Map<String, Object> map) throws FileNotFoundException {
        try {
            List<String> files = (List<String>) map.get("files");
            List<Map<String, Object>> dir = (List<Map<String, Object>>) map.get("dir");
            String filepath = (String) map.get("path");
            File file = new File(filepath);
            // 如果这个文件不是目录，则进行如下操作
            if (!file.isDirectory()) {
                files.add(file.getPath());
            } else if (file.isDirectory()) {
                String[] fileList = file.list();
                if (fileList == null) {
                    return ;
                }
                for (String s : fileList) {
                    File readfile = new File(filepath + "\\" + s);
                    if (!readfile.isDirectory()) {
                        files.add(readfile.getPath());
                    } else if (readfile.isDirectory()) {
                        Map<String, Object> subMap = new HashMap<>();
                        subMap.put("files", new ArrayList<String>());
                        subMap.put("dir", new ArrayList<HashMap<String, Object>>());
                        subMap.put("path", readfile.getPath());
                        dir.add(subMap);
                        readFile(subMap);
                    }
                }
            }
        } catch (FileNotFoundException e) {
           throw new BaseException("读取文件路径出错！");
        }
    }
}